package app.controller.city;

import app.entity.UserSession;
import app.service.DeviceManageService;
import app.service.FacilitiesManageService;
import app.utils.Common;
import app.utils.DataResponse;
import app.utils.TimeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import common.standard.table.DeviceBugFieldEnum;
import common.standard.table.DeviceNumFieldEnum;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import refactor.entity.DeviceBug;
import refactor.entity.DeviceNum;
import refactor.service.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 这个类用于city用户登录成功之后跳转到的index页面上的所有同步和异步请求的处理
 * @author 昊琦
 *创建时间：2018年3月7日10:02:31
 */
@Controller
public class IndexCity {
	
	private static final Log logger = LogFactory.getLog(IndexCity.class);

	@Autowired
	@Qualifier("DeviceManageService")
	private DeviceManageService dms;

	private IReadMeterService readMeterService;

	@Autowired
	public void setReadMeterService(IReadMeterService readMeterService) {
		this.readMeterService = readMeterService;
	}

	@Autowired
	@Qualifier("FacilitiesManageService")
	private FacilitiesManageService fms;

	private IFacMonitoringService facMonitoringService;

	@Autowired
	public void setFacMonitoringService(IFacMonitoringService facMonitoringService) {
		this.facMonitoringService = facMonitoringService;
	}

	private IDeviceBugService deviceBugService;

	@Autowired
	public void setDeviceBugService(IDeviceBugService deviceBugService) {
		this.deviceBugService = deviceBugService;
	}

	private IFacilitiesService facilitiesService;

	@Autowired
	public void setFacilitiesService(IFacilitiesService facilitiesService) {
		this.facilitiesService = facilitiesService;
	}

	private IDeviceNumService deviceNumService;

	@Autowired
	public void setDeviceNumService(IDeviceNumService deviceNumService) {
		this.deviceNumService = deviceNumService;
	}

	private IEventLogService eventLogService;

	@Autowired
	public void setEventLogService(IEventLogService eventLogService) {
		this.eventLogService = eventLogService;
	}

	/**
	 * 获取各个模块设备类型和数量
	 * @param response
	 * @param session
	 */
	@GetMapping(value="ajaxdevicetype")
	public void  getDeviceType(HttpServletResponse response,HttpSession session) {
		
		//根据session获取用户所属地区
		UserSession userSession = (UserSession) session.getAttribute(Common.sessionUser);
		
		//没有登陆,返回空JSON
		if (userSession==null) {
			DataResponse.jsonResponse(response, "");
		}else{
			int regionId = userSession.getRegionId();
			//根据地区查询当地各模块设备数量
			QueryWrapper<DeviceNum> deviceNumQueryWrapper = new QueryWrapper<DeviceNum>().eq(DeviceNumFieldEnum.REGIONID.getFieldName(), regionId);
			List<DeviceNum> list = deviceNumService.list(deviceNumQueryWrapper);
			DataBean data = new DataBean();
			for (DeviceNum devicenum : list) {
				data.addData(devicenum.getType(), devicenum.getNum());
			}
			
//			//查询电表数量
//			int count = readMeterService.count();
//			data.addData("远程抄表", (long) count);
			
			DataResponse.jsonResponse(response, data);
			
			logger.info("ajaxdevicetype接口调用完成");
		}

	}
	
	
	/**
	 * 获取各个模块的硬件故障数量
	 * @param response
	 * @param session
	 */
	@GetMapping("ajaxbugrate")
	public void getBugRate(HttpServletResponse response,HttpSession session){
		
		//获取用户的所属地区
		UserSession userSession=(UserSession)session.getAttribute(Common.sessionUser);
		
		//没有登陆,返回空JSON
		if (userSession==null) {
			DataResponse.jsonResponse(response, "");
		}else{
			int regionId = userSession.getRegionId();
			//根据地区查询硬件故障
			List<DeviceBug> listDevBug = deviceBugService.list(new QueryWrapper<DeviceBug>().eq(DeviceBugFieldEnum.REGIONID.getFieldName(), regionId));

			PieDataBean pieDataBean = new PieDataBean();
			
			for (DeviceBug devbug : listDevBug) {

//				if(devbug.getName().contains("机房")) {
//					List<DeviceNum> list = deviceNumService.list(new QueryWrapper<DeviceNum>().eq(DeviceNumFieldEnum.REGIONID.getFieldName(), regionId));
//					for(DeviceNum num:list) {
//						if (num.getType().contains("机房")) {
//							int size = deviceOnline().size();
//							pieDataBean.addData(num.getType(), num.getNum()-size);
//						}
//					}
//
//					continue;
//				}

				pieDataBean.addData(devbug.getName(), devbug.getNum());
			}
	//		pieDataBean.addData("远程抄表", 0L);
			
			
			DataResponse.jsonResponse(response, pieDataBean);
		}
		
		
		logger.info("ajaxdevbug接口调用完成");
	}
	
	
	/**
	 * 统计最近days天的每天的告警记录次数
	 * @param days
	 * @throws ParseException 
	 */
	@PostMapping("ajaxwarningchartdata")
	public void countWarningMess(@RequestParam(value="days",defaultValue="30")int days,HttpServletResponse response,HttpSession session) throws ParseException{
		
		//获取用户所属的地区
		UserSession userSession = (UserSession)session.getAttribute(Common.sessionUser);

		//没有登陆,返回空JSON
		if (userSession==null) {
			DataResponse.jsonResponse(response, "");
		}else{
			int regionId=userSession.getRegionId();
			//获取到regeionId则走以下流程
			List<List<String>> res = new ArrayList<>();
			List<String> values = new ArrayList<>();
			List<String> date = new ArrayList<>();
			res.add(date);
			res.add(values);
			
			//获取当前时间
			long timeLongNow = TimeUtils.getNowDateLong();
			//计算days前的当天00点的时间
			long timeLongDays = timeLongNow-(days*24*3600*1000L);
			String timeStrDays = TimeUtils.formatTime(timeLongDays, "yyyy-MM-dd");
			timeStrDays+=" 00:00:00";
			timeLongDays = TimeUtils.StringToLong(timeStrDays, "yyyy-MM-dd HH:mm:ss");
			//一次性将数据获取出来再做删选（只访问一次数据库）
            List<Map<String, Object>> sqlWithResult = eventLogService.getWarningMessage(regionId);
			
			//遍历获取到的结果，并设置count计数，将取出的数据按日期筛选
			long ts = timeLongDays; 
			long te = timeLongDays+(24 * 3600 * 1000L);
			int count =0;
			for(int index=0;index<sqlWithResult.size();index++){

				long time = Long.parseLong(sqlWithResult.get(index).get("startTime").toString());
				
				if (time<ts){
					
				}else if (time>=ts&&time<te){
					count++;
					
				}else if (time>=te) {
					//把数据放入list
					values.add(count+"");
					date.add(TimeUtils.formatTime(ts, "yyyy-MM-dd"));
					
					//更新计数和时间段
					ts=te;
					te =te+(24 * 3600 * 1000L);
					count =0;
					index--;
				}
			}
			
			//返回Json数据
			DataResponse.jsonResponse(response, res);
			
			logger.info("ajaxwarningchartdata接口调用完成");
		}	
		
	}
	
	/**
	 * 获取设施类别和数量在首页的统计图显示
	 * @param response
	 * @param session
	 */
	@PostMapping("ajaxfactypechartdata")
	public void countFacGroupNum(HttpServletResponse response,HttpSession session){
		
		//从session里获取用户信息
		UserSession userSession = (UserSession)session.getAttribute(Common.sessionUser);
		
		if (userSession==null) {
			//如果没有登录，返回空json
			DataResponse.jsonResponse(response, "");
		}else{
			//如果登录
			
			//获取regionId
			int regionId = userSession.getRegionId();
			
			List<Map<String, Object>> facGroup = facilitiesService.countFacilitiesGroupNum(regionId);
			
			//返回json
			DataResponse.jsonResponse(response, facGroup);
			
		}
		
		logger.info("ajaxfactypechartdata接口调用完成");
	}
	
	/**
	 * 获取设备和设施的告警信息文本
	 * @param response
	 * @param session
	 */
	@PostMapping("ajaxwarningtextdata")
	public void getWarningText(HttpServletResponse response,HttpSession session){
		
		//从session里获取用户信息
		UserSession userSession =  (UserSession)session.getAttribute(Common.sessionUser);
		
		if (userSession==null) {
			//如果session为空，返回空json
			DataResponse.jsonResponse(response, "");
		}else{
			//如果session不为空
			int regionId = userSession.getRegionId();
			
			//根据region 查询告警记录
			List<Map<String, Object>> templist =  facMonitoringService.getWarningText(regionId);
			
			//遍历templist，拼接里面的信息
			List<String> textList = new ArrayList<>();
			int count =1;
			for (Map<String, Object> result : templist) {
				
				String devCode = result.get("devCode").toString();
				String modName = result.get("modName").toString();
				String msg = result.get("msg").toString();
				String facDesc = result.get("facDesc").toString();
				
				String content = count+"    设备： "+devCode+"  模块： "+modName+"  信息： "+msg+"  设施： "+facDesc;
				count++;
				//将最后拼接好的信息放入list
				textList.add(content);
			}
			
			//返回json
			DataResponse.jsonResponse(response, textList);
			
			
		}
		
		logger.info("ajaxwarningtextdata接口调用完成");
	}
	
	
	
	/**
	 * 用于存放设备模块数量和类型
	 * @author dell
	 *
	 */
	public class DataBean {
		public DataBean(){};
		public void addData(String name,Long num){
			categories.add(name);
			series.getData().add(num);
		}
		public List<String> categories=new ArrayList<>();
		public Series series=new Series();
		
		public List<String> getCategories() {
			return categories;
		}
		public void setCategories(List<String> categories) {
			this.categories = categories;
		}
		
		public Series getSeries() {
			return series;
		}
		public void setSeries(Series series) {
			this.series = series;
		}


		public class Series{
			private String type="bar";
			private String barWidth ="30";
			private List<Long> data=new ArrayList<>();
			public String getType() {
				return type;
			}
			public void setType(String type) {
				this.type = type;
			}
			public List<Long> getData() {
				return data;
			}
			public void setData(List<Long> data) {
				this.data = data;
			}
			public String getBarWidth() {
				return barWidth;
			}
			public void setBarWidth(String barWidth) {
				this.barWidth = barWidth;
			}
			
		}
	}
	
	/**
	 * 用于存放模块的硬件故障数据
	 * @author dell
	 *
	 */
	public class PieDataBean {

		public class DataPair {
			private String name;
			private Number value;

			public DataPair(String name, Number value) {
				super();
				this.name = name;
				this.value = value;
			}

			public String getName() {
				return name;
			}

			public void setName(String name) {
				this.name = name;
			}

			public Number getValue() {
				return value;
			}

			public void setValue(Number value) {
				this.value = value;
			}
		}

		private List<DataPair> data;
		private List<String> legend;

		public PieDataBean() {
			super();
			data = new ArrayList<DataPair>();
			legend = new ArrayList<String>();
		}

		void addData(String str, Number val) {
			data.add(new DataPair(str, val));
			legend.add(str);
		}

		public List<DataPair> getData() {
			return data;
		}

		public void setData(List<DataPair> data) {
			this.data = data;
		}

		public List<String> getLegend() {
			return legend;
		}

		public void setLegend(List<String> legend) {
			this.legend = legend;
		}
		
	}
	//获取在线设备
	private List<String> deviceOnline(){
		List<String> res=new ArrayList<>();
		try {
			URL url=new URL("https://www.3firelink.com/AcceptTransmitServer/LockCondition");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("token_key", "aqscxkz");
			InputStream stream = connection.getInputStream();
			int len=0;
			byte[] buff=new byte[20];
			StringBuilder builder=new StringBuilder();
			while((len=stream.read(buff))>0) {
				builder.append(new String(buff, 0,len));
			}
			//{"devCodes":[]}
			JsonParser parser=new JsonParser();
			JsonArray devs = parser.parse(builder.toString()).getAsJsonObject().get("devCodes").getAsJsonArray();
			for(JsonElement JE:devs) {
				String devCode = JE.getAsString();
				res.add(devCode);
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {

			return res;
		}
		
		
	}
}


